package com.shensi.appCollect.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shensi.appCollect.pojo.AppUserInfo;
import com.shensi.appCollect.dao.AppUserInfoMapper;
import com.shensi.appCollect.dao.LabelMapper;
import com.shensi.appCollect.dao.SysDictDataMapper;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.service.BusinessAuditService;
import com.shensi.appCollect.service.LabelService;
import com.shensi.appCollect.utils.StringUtils;
import com.shensi.appCollect.utils.exception.CustomException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;


/**
 * (BusinessAudit)表控制层
 *
 * @author makejava
 * @since 2023-12-19 16:26:28
 */
@RestController
@RequestMapping("businessAudit")
@Api(tags = "审核")
@Slf4j
public class BusinessAuditController {
    /**
     * 服务对象
     */
    @Resource
    private BusinessAuditService businessAuditService;

    @Resource
    private LabelService labelService;

    @Resource
    private LabelMapper labelMapper;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Resource
    private AppUserInfoMapper appUserInfoMapper;



    /**
     * 分页查询
     *
     * @param businessAudit 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<BusinessAudit>> queryByPage(BusinessAudit businessAudit, PageRequest pageRequest) {
        return ResponseEntity.ok(this.businessAuditService.queryByPage(businessAudit, pageRequest));
    }

    @PostMapping("/query")
    public ResponseEntity<List<BusinessAudit>> query(BusinessAudit businessAudit) {
        return ResponseEntity.ok(this.businessAuditService.query(businessAudit));
    }

    @GetMapping("/queryById/{LabelId}")
    public ResponseEntity<LabelRule> queryLabelRuleById(@PathVariable("LabelId") Long LabelId) {
        return ResponseEntity.ok(labelService.queryLabelRuleById(LabelId));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<BusinessAudit> queryById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(this.businessAuditService.queryById(id));
    }

    @PostMapping("/queryLatestAudit")
    public ResponseEntity<Map> queryLatestAudit(@RequestBody BusinessAudit businessAudit){
        Map<String,Object> m=new HashMap<>();
        Long userId = businessAudit.getUserId();
        AppUserInfo appUserById = appUserInfoMapper.getAppUserById(userId);
        if(StringUtils.isEmpty(businessAudit.getBusinessName())||
                businessAudit.getUserId()==null){
            throw new CustomException("参数错误");
        }

        businessAudit = this.businessAuditService.queryLatestAudit(businessAudit);

        m.put("code",200);
        m.put("msg","success");
        if(businessAudit==null||!businessAudit.getStatus().equals("PASS")){
            if(appUserById!=null&&StringUtils.isNotEmpty(appUserById.getMobilePhone())){
                //List<LabelRule> labelRuleList=labelMapper.getLabelRuleByPhone(appUserById.getMobilePhone());
                CustomerLabel customerLabel=new CustomerLabel();
                customerLabel.setPhone(appUserById.getMobilePhone());
                customerLabel.setEnterpriseId(appUserById.getStationId());
                customerLabel.setDelFlag("0");
                List<CustomerLabel> customerLabelList = labelMapper.getCustomerLabelList(customerLabel);
                if(customerLabelList.size()>0){
                    businessAudit=new BusinessAudit();
                    businessAudit.setStatus("PASS");
                    businessAudit.setLabelName(customerLabelList.get(0).getLabelName());
                    businessAudit.setCategoryName(customerLabelList.get(0).getCategoryName());
                    businessAudit.setAuditTime(customerLabelList.get(0).getCreateTime());
                    businessAudit.setCreateTime(customerLabelList.get(0).getCreateTime());
                    m.put("result",businessAudit);
                }
            }
        }
        if(businessAudit != null){
            m.put("result",businessAudit);
        }else{
            m.put("result",null);
        }
        return ResponseEntity.ok(m);
    }

    /**
     * 新增数据
     *
     * @param businessAudit 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Map> add(@RequestBody BusinessAudit businessAudit) {
        if(StringUtils.isEmpty(businessAudit.getBusinessName())||businessAudit.getBusinessId()==null
                ||businessAudit.getEnterpriseId()==null||StringUtils.isEmpty(businessAudit.getMobilePhone())){
            throw new CustomException("参数错误");
        }
        BusinessAudit auditQuery=new BusinessAudit();
        auditQuery.setMobilePhone(businessAudit.getMobilePhone());
        List<BusinessAudit> list=businessAuditService.queryByMobilePhone(businessAudit.getMobilePhone());
        if(list.size()>0){//审核成功之后也可能会被移出渠道，这种情况可以重新加入渠道
            Map<String,Object> m=new HashMap<>();
            m.put("code",500);
            m.put("msg","该手机号已经在审核中");
            return ResponseEntity.ok(m);
        }
        CustomerLabel customerLabel = new CustomerLabel();
        customerLabel.setPhone(businessAudit.getMobilePhone());
        customerLabel.setEnterpriseId(businessAudit.getEnterpriseId().intValue());
        customerLabel.setLabelId(businessAudit.getBusinessId()+"");
        customerLabel.setDelFlag("0");//查还在渠道里可用的用户
        List<CustomerLabel> customerLabelList = labelMapper.getCustomerLabelList(customerLabel);
        if(customerLabelList.size()>0){
            Map<String,Object> m=new HashMap<>();
            m.put("code",500);
            m.put("msg","该手机号已经加入渠道");
            return ResponseEntity.ok(m);
        }

        businessAudit.setCreateTime(new Date());
        businessAudit.setStatus("IN_REVIEW");
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }

        String ordNo = System.currentTimeMillis() + result;
        businessAudit.setOrderNo(ordNo);
        BusinessAudit insert = this.businessAuditService.insert(businessAudit);
        Map<String,Object> m=new HashMap<>();
        m.put("code",200);
        m.put("result",insert);
        m.put("msg","success");
        return ResponseEntity.ok(m);
    }

    /**
     * 新增数据
     *
     * @param businessAudit 实体
     * @return 新增结果
     */
    @PostMapping("/addBusinessV2")
    public ResponseEntity<Map> addBusiness(@RequestBody BusinessAudit businessAudit) {
        if(businessAudit.getUserId()==null || businessAudit.getBusinessId()==null
                ||businessAudit.getEnterpriseId()==null){
            throw new CustomException("参数错误");
        }
        BusinessAudit auditQuery=new BusinessAudit();
        auditQuery.setMobilePhone(businessAudit.getMobilePhone());
        List<BusinessAudit> list=businessAuditService.queryByMobilePhone(businessAudit.getMobilePhone());
        if(list.size()>0){
            Map<String,Object> m=new HashMap<>();
            m.put("code",500);
            m.put("msg","该手机号已经在审核中或审核通过");
            return ResponseEntity.ok(m);
        }

        CustomerLabel label = new CustomerLabel();
        label.setPhone(businessAudit.getMobilePhone());
        label.setEnterpriseId(businessAudit.getEnterpriseId().intValue());
        label.setLabelId(businessAudit.getBusinessId()+"");
        label.setDelFlag("0");
        List<CustomerLabel> customerLabelList = labelMapper.getCustomerLabelList(label);
        if(customerLabelList.size()>0){
            Map<String,Object> m=new HashMap<>();
            m.put("code",500);
            m.put("msg","该手机号已经加入渠道");
            return ResponseEntity.ok(m);
        }

        AppUserInfo appUserById = appUserInfoMapper.getAppUserById(businessAudit.getUserId());
        CustomerLabel customerLabel = new CustomerLabel();
        customerLabel.setPhone(appUserById.getMobilePhone());
        customerLabel.setEnterpriseId(businessAudit.getEnterpriseId().intValue());
        customerLabel.setLabelId(businessAudit.getBusinessId()+"");
        customerLabel.setCreateBy(appUserById.getName());
        customerLabel.setCreateTime(new Date());
        customerLabel.setDelFlag("0");
        labelService.insertCustomerLabel(customerLabel);
        Map<String,Object> m=new HashMap<>();
        m.put("code",200);
        m.put("msg","success");
        return ResponseEntity.ok(m);
    }
    /**
     * 编辑数据
     *
     * @param businessAudit 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<BusinessAudit> edit(BusinessAudit businessAudit) {
        return ResponseEntity.ok(this.businessAuditService.update(businessAudit));
    }

    @GetMapping("/queryLabelRuleType")
    public ResponseEntity<Map> queryLabelRuleType(){
        List<SysDictData> label_rule_type = sysDictDataMapper.selectDictDataByType("label_rule_type");
        Map<String,Object> m=new HashMap<>();
        m.put("code",200);
        m.put("result",label_rule_type);
        m.put("msg","success");
        return ResponseEntity.ok(m);
    }

    /**
     * 删除数据
     *

     * @return 删除是否成功
     */
/*    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Long id) {
        return ResponseEntity.ok(this.businessAuditService.deleteById(id));
    }*/
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<String> handleUserNotFoundException(CustomException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }

    /**
     * 查询用户渠道申请记录（功能设计太不合理，导致情况有点多）
     * @param businessAudit
     * @return
     */
    @PostMapping("/queryLatestAuditNew")
    public ResponseEntity<Map> queryLatestAuditNew(@RequestBody BusinessAudit businessAudit) {
        log.info("查询用户渠道申请记录:/queryLatestAuditNew:" + JSON.toJSONString(businessAudit));
        if (StringUtils.isEmpty(businessAudit.getBusinessName()) || businessAudit.getUserId() == null) {
            throw new CustomException("参数错误");
        }
        Long labelId = businessAudit.getBusinessId();//扫渠道码加入---查询时必传
        Map<String, Object> m = new HashMap<>();
        List<BusinessAudit> resData = new ArrayList<>();

        AppUserInfo appUser = appUserInfoMapper.getAppUserById(businessAudit.getUserId());
        if (null == appUser) {
            throw new CustomException("用户不存在！");
        }

        // pc分配和扫渠道码都可以加入到渠道，且还不需要审核，不会在审核记录表里有数据
        // （首先查渠道用户分配明细表，该表没有存用户id,只能先查该用户微信绑定的手机号的记录）
        CustomerLabel customerLabel = new CustomerLabel();
        customerLabel.setPhone(appUser.getMobilePhone());
        customerLabel.setEnterpriseId(appUser.getStationId());
        customerLabel.setDelFlag("0");
        List<CustomerLabel> customerLabelList = labelMapper.getCustomerLabelList(customerLabel);
        BusinessAudit businessAuditData = null;
        if (null != customerLabelList && customerLabelList.size() > 0) {
            businessAuditData = new BusinessAudit();
            businessAuditData.setUserId(businessAudit.getUserId());
            businessAuditData.setMobilePhone(customerLabelList.get(0).getPhone());
            businessAuditData.setStatus("PASS");
            businessAuditData.setAuditTime(customerLabelList.get(0).getCreateTime());
            businessAuditData.setCreateTime(customerLabelList.get(0).getCreateTime());
            businessAuditData.setBusinessName(customerLabelList.get(0).getLabelName());
            businessAuditData.setBusinessId(Long.valueOf(customerLabelList.get(0).getLabelId()));
            resData.add(businessAuditData);
        }

        //扫渠道码加入渠道，手机号必定是微信用户绑定的手机号appUser.getMobilePhone()（查到已经存在渠道中，直接返回）
        if (null != labelId && null != businessAuditData) {
            m.put("result", resData);
            m.put("code", 200);
            m.put("msg", "success");
            return ResponseEntity.ok(m);
        }

        //有审核记录的场景两种
        //1.公众号点渠道认证申请加入（可以随便填手机号，可填自己的，也可填别人的，原有设计，无法变更）
        //2.后台渠道列表菜单-打开审核开关，扫渠道码加入（必须是微信绑定手机号）
        // 查询渠道加入申请审核记录表
        //最后需要将综合数据返回（有审核记录和没有审核记录，没有的补上）
        businessAudit = businessAuditService.queryLatestAudit(businessAudit);
        if (null != businessAudit) {
            // 由于目前都是取最后一条审核记录
            // 如果用户先从公众号加了一条，又扫码加一条（只能取到扫码这条审核记录）
            // 要展示公众号请求过来的记录，需要补一条
            if (null == labelId && null != businessAudit.getSource() && 2 == businessAudit.getSource()) {
                // 如果最后一条来源是渠道扫码加入的，需要在往前查一条，有可能在渠道扫码加入之前会存在公众号过来的审核记录
                BusinessAudit whereis = new BusinessAudit();
                whereis.setUserId(appUser.getUserId().longValue());
                whereis.setMobilePhone(appUser.getMobilePhone());
                BusinessAudit businessAuditGzh = businessAuditService.getGzhBusinessAudit(whereis);
                //补一条失败记录（成功的话）
                if (null != businessAuditGzh) {
                    LabelRule labelRulesGzh = labelMapper.getLabelNameById(businessAuditGzh.getBusinessId().intValue());
                    log.info("渠道信息！labelRulesGzh:" + JSONObject.toJSONString(labelRulesGzh));
                    if (null != labelRulesGzh) {//如果渠道被删除了，申请审核的记录也不用管了
                        BusinessAudit busAGzh = new BusinessAudit();
                        busAGzh.setUserId(businessAuditGzh.getUserId());
                        busAGzh.setMobilePhone(businessAuditGzh.getMobilePhone());
                        busAGzh.setStatus(businessAuditGzh.getStatus());
                        busAGzh.setAuditTime(businessAuditGzh.getAuditTime());
                        busAGzh.setCreateTime(businessAuditGzh.getCreateTime());
                        busAGzh.setBusinessName(null == labelRulesGzh ? null : labelRulesGzh.getLabelName());
                        busAGzh.setBusinessId(businessAuditGzh.getBusinessId());
                        busAGzh.setAuditOpinion(businessAuditGzh.getAuditOpinion());
                        if ("PASS".equals(businessAuditGzh.getStatus())) {
                            customerLabel.setPhone(businessAuditGzh.getMobilePhone());
                            List<CustomerLabel> notUserPhoneDatas = labelMapper.getCustomerLabelList(customerLabel);
                            if (null != notUserPhoneDatas && notUserPhoneDatas.size() > 0) {
                                //可能会被手动移除和分配，时间取最新的
                                busAGzh.setAuditTime(notUserPhoneDatas.get(0).getCreateTime());
                                busAGzh.setCreateTime(notUserPhoneDatas.get(0).getCreateTime());
                                resData.add(busAGzh);
                            }
                        }
                        if ("FAIL".equals(businessAuditGzh.getStatus())) {
                            resData.add(busAGzh);
                        }
                    }
                }
            }

            LabelRule labelRules = labelMapper.getLabelNameById(businessAudit.getBusinessId().intValue());
            log.info("渠道信息！labelRules:" + JSONObject.toJSONString(labelRules));
            if (null != labelRules) {//如果渠道被删除了，申请审核的记录也不用管了
                BusinessAudit busA = new BusinessAudit();
                busA.setUserId(businessAudit.getUserId());
                busA.setMobilePhone(businessAudit.getMobilePhone());
                busA.setStatus(businessAudit.getStatus());
                busA.setAuditTime(businessAudit.getAuditTime());
                busA.setCreateTime(businessAudit.getCreateTime());
                busA.setBusinessName(labelRules.getLabelName());
                busA.setBusinessId(businessAudit.getBusinessId());
                busA.setAuditOpinion(businessAudit.getAuditOpinion());

                if ("PASS".equals(businessAudit.getStatus())) {//审核通过还需要查询是否被手动移除
                    if (null != labelId) {
                        //情况1：存在一条不同手机号加入渠道的成功记录（互不影响，可以申请加入，直接返回null）
                        //情况2：存在一条相同手机号加入渠道的成功记录，但是被手动移除了（可以再次申请加入，直接返回null）
                        m.put("result", null);
                        m.put("code", 200);
                        m.put("msg", "success");
                        return ResponseEntity.ok(m);
                    }

                    if (!businessAudit.getMobilePhone().equals(appUser.getMobilePhone())) {
                        customerLabel.setPhone(businessAudit.getMobilePhone());
                        List<CustomerLabel> notUserPhoneDatas = labelMapper.getCustomerLabelList(customerLabel);
                        if (null != notUserPhoneDatas && notUserPhoneDatas.size() > 0) {
                            //可能会被手动移除和分配，时间取最新的
                            busA.setAuditTime(notUserPhoneDatas.get(0).getCreateTime());
                            busA.setCreateTime(notUserPhoneDatas.get(0).getCreateTime());
                            resData.add(busA);
                        }
                    }
                }
                if ("FAIL".equals(businessAudit.getStatus())) {//审核失败
                    //审核失败了，但是分配明细表里有记录，可能是pc手动分配的，这种情况就作为成功处理（排除，businessAuditData最上面已处理）
                    if (!(null != businessAuditData && businessAudit.getMobilePhone().equals(appUser.getMobilePhone()))) {
                        resData.add(busA);
                    }
                }
                if ("IN_REVIEW".equals(businessAudit.getStatus())) {//待审核
                    //该用户绑定的手机号不在任何渠道，通过扫渠道码加入,渠道是不需要进行审核，但是该用户已经存在一条其他手机号的待审核的记录，互不影响，直接返回null，扫码直接加入
                    if (null != labelId) {
                        LabelRule lr = labelMapper.getLabelNameById(labelId.intValue());
                        log.info("渠道信息！lr:" + JSON.toJSONString(lr));
                        if (null != lr && !businessAudit.getMobilePhone().equals(appUser.getMobilePhone())) {
                            if (null != lr.getIsAudit() && 0 == lr.getIsAudit()) {//不需要审核
                                m.put("result", null);
                                m.put("code", 200);
                                m.put("msg", "success");
                                return ResponseEntity.ok(m);
                            }
                        }
                    }
                    resData.add(busA);
                }
            }
        }
        if (resData.size() < 1) {
            resData = null;
        }
        m.put("result", resData);
        m.put("code", 200);
        m.put("msg", "success");
        return ResponseEntity.ok(m);
    }

}

